﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using AutocompleteDemo;
using AjaxControlToolkit;
using System.ComponentModel;
using System.Web.UI.WebControls;

namespace AutoCompletionDemoTest.Layouts.AutoCompletionDemoTest
{
    public partial class Test : LayoutsPageBase
    {
        AutoCompleteExtender completeCity;
        AutoCompleteExtender completeState;

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            completeState = new AutoCompleteExtender();
            completeState.ServicePath = GetServiceEndpointPath(); 
            completeState.ServiceMethod = "GetStates";
            completeState.TargetControlID = "InputFormTextBoxState";
            completeState.MinimumPrefixLength = 0;
            completeState.BehaviorID = "AutoCompleteState";
            completeState.CompletionInterval = 1000;
            completeState.EnableCaching = true;
            PlaceHolderStateExtender.Controls.Add(completeState);

            completeCity = new AutoCompleteExtender();
            completeCity.ServicePath = GetServiceEndpointPath();
            completeCity.ServiceMethod = "GetCitiesForState";
            completeCity.TargetControlID = "InputFormTextBoxCity";
            completeCity.MinimumPrefixLength = 0;
            completeCity.BehaviorID = "AutoCompleteCity";
            completeCity.CompletionInterval = 1000;
            completeCity.EnableCaching = true;
            PlaceHolderCityExtender.Controls.Add(completeCity);
        }

        protected void InputFormTextBoxState_TextChanged(object sender, EventArgs e)
        {
            completeCity.ContextKey = InputFormTextBoxState.Text;
            InputFormTextBoxCity.Text = string.Empty;
            InputFormTextBoxCity.Focus(); 
        }

        private string GetServiceEndpointPath()
        {
            AutoCompletionServiceApplicationProxy proxy = 
                AutoCompletionServiceApplicationProxy.GetProxy(SPServiceContext.Current);
            AutoCompletionServiceApplication app = proxy.AutoCompletionApplication;

            return app.DefaultServicePath.ToString();
        }
    }
}
